package com.fengniao.file.controller;

import com.fengniao.file.def.FastDFSFile;
import com.fengniao.file.util.FastDFSUtil;
import entity.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lanhai
 * @date 2021/7/4 23:13
 */
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class FileUploadController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {

        // 1.封装文件到FastDFSFile中
        FastDFSFile fastDFSFile = new FastDFSFile(
                file.getOriginalFilename(), // 文件名
                file.getBytes(), // 文件字节数组
                // 获取文件扩展名
                StringUtils.getFilenameExtension(
                        file.getOriginalFilename())
        );

        // 2.调用FastDFSUtil工具类将文件上传到FastDFS中
        String[] uploads = FastDFSUtil.upload(fastDFSFile);

        // 3.拼接访问图片的url
        String url = FastDFSUtil.getTrackerInfo()  + "/" + uploads[0] +
                "/" + uploads[1];
        return Result.ok("上传成功").setData(url);
    }


}
